package com.yuwj.chinaa.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.othershe.nicedialog.BaseNiceDialog;
import com.othershe.nicedialog.NiceDialog;
import com.othershe.nicedialog.ViewConvertListener;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.yuwj.chinaa.R;
import com.yuwj.chinaa.base.BaseActivity;
import com.yuwj.chinaa.base.ConstantParam;
import com.yuwj.chinaa.entity.EntityOrderDetail;
import com.yuwj.chinaa.entity.EntityOrderWithTrade;
import com.yuwj.chinaa.presenter.IPresenter;
import com.yuwj.chinaa.presenter.presenterImpl.PresenterImpl;
import com.yuwj.chinaa.util.PhoneUtil;
import com.yuwj.chinaa.util.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

//出售交易详情
public class TradeWithSellDetailActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_gte_amount)
    TextView tvTradeAmount;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_trade_state)
    TextView tvState;
    @BindView(R.id.tv_trade_count)
    TextView tvTradeCount;
    @BindView(R.id.tv_order_no)
    TextView tvOrderNo;
    @BindView(R.id.tv_match_order_no)
    TextView tvMatchTradeNo;
    @BindView(R.id.tv_trade_tip)
    TextView tvTradeTip;
    @BindView(R.id.civ_user_photo)
    CircleImageView civUserPhoto;
    @BindView(R.id.tv_name)
    TextView tvRealName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_alipay_name)
    TextView tvAlipayName;
    @BindView(R.id.tv_alipay_account)
    TextView tvAlipayAccount;
    @BindView(R.id.tv_bank_name)
    TextView tvBankName;
    @BindView(R.id.tv_bank_username)
    TextView tvBankUserNmae;
    @BindView(R.id.tv_bank_account)
    TextView tvBankAccount;
    @BindView(R.id.iv_buyer_pay_screen_spot)
    ImageView ivBuyerScreenSpot;
    @BindView(R.id.ll_buyer_pay_screen_spot)
    LinearLayout llBuyerScrrenSpot;
    @BindView(R.id.tv_left_button)
    TextView tvLeftButton;
    @BindView(R.id.tv_right_button)
    TextView tvRightButton;
    @BindView(R.id.ll_has_sell)
    LinearLayout llHasSell;
    @BindView(R.id.ll_operator_container)
    LinearLayout llOperatorContainer;
    @BindView(R.id.tv_userno)
    TextView tvUserno;

    AlertDialog alertDialogWithShowQrCode;
    String orderId;
    EntityOrderDetail orderDetail;//交易买卖双方账户明细
    IPresenter presenter;
    boolean isReleaseBiSuccess = false;//放币释放成功

    @Override
    public int setCustomContentViewResourceId() {
        return R.layout.activity_trade_with_sell_detail;
    }


    public static Intent createIntent(Context context, String orderId) {
        Intent intent = new Intent(context, TradeWithSellDetailActivity.class);
        intent.putExtra("orderId", orderId);

        return intent;
    }

    @Override
    public void initParam() {
        presenter = new PresenterImpl(this);
        orderId = getIntent().getStringExtra("orderId");
    }

    @Override
    public void initView() {
    }

    @Override
    public void initOperator() {
        JSONObject param = new JSONObject();
        try {
            param.put("orderId", orderId + "");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        //卖家或买家查看订单明细
        presenter.queryOrderDetail(param.toString());

    }

    //更新支付信息详情
    public void updatePayInfoView() {
        if (orderDetail != null) {
            tvTradeAmount.setText(orderDetail.getBiCountRMB() + " CNY");
            tvPrice.setText("价格：" + orderDetail.getBiPrice() + " CNY");
            tvTradeCount.setText("数量：" + orderDetail.getBiCount() + " china-A");
            tvTitle.setText("向" + orderDetail.getMatchingUserName() + "出售china-A");
            tvOrderNo.setText("订单号：" + orderDetail.getOrderNo());
            tvMatchTradeNo.setText("匹配单号：" + orderDetail.getMatchingOrderNo());
            Glide.with(context).load("").error(R.mipmap.ic_asset_user_photo).into(civUserPhoto);
            tvRealName.setText(orderDetail.getAuthUserName());
            tvUserno.setText(orderDetail.getMatchingUserNo());
            tvPhone.setText(orderDetail.getMatchingUserPhone());
            tvAlipayName.setText(orderDetail.getAuthUserName());
            tvAlipayAccount.setText(orderDetail.getAuthAliPayAccount());
            tvBankName.setText(orderDetail.getAuthBankName());
            tvBankUserNmae.setText(orderDetail.getAuthUserName());
            tvBankAccount.setText(orderDetail.getAuthBankNo());


            switch (orderDetail.getPayStatus()) {
                case 0://0-未付款,1-已付款
                    tvState.setText("待付款");
                    tvTradeTip.setText("对方将在规定时间内完成付款，未收到款请勿释放china-A");
                    ivBuyerScreenSpot.setVisibility(View.GONE);
                    llBuyerScrrenSpot.setVisibility(View.GONE);
                    tvLeftButton.setVisibility(View.GONE);
                    tvRightButton.setText("等待对方付款");
                    tvRightButton.setBackgroundResource(R.mipmap.ic_trade_confirm_pay_btn_unable_bg);
                    llHasSell.setVisibility(View.GONE);
                    break;
                case 1://0-未付款,1-已付款
                    if (isReleaseBiSuccess) {
                        tvState.setText("已放币");
                        tvTradeTip.setText("对方已付款，确认收款后已释放china-A");
                        if (!TextUtils.isEmpty(orderDetail.getPaySuccessImg())) {
                            ivBuyerScreenSpot.setVisibility(View.VISIBLE);
                            llBuyerScrrenSpot.setVisibility(View.VISIBLE);
                            Glide.with(context).load(orderDetail.getPaySuccessImg()).error(R.mipmap.ic_alipay).into(ivBuyerScreenSpot);
                        } else {
                            ivBuyerScreenSpot.setVisibility(View.GONE);
                            llBuyerScrrenSpot.setVisibility(View.GONE);
                        }
                        tvRightButton.setVisibility(View.GONE);
                        tvLeftButton.setVisibility(View.GONE);
                        llHasSell.setVisibility(View.VISIBLE);
                    } else {
                        tvState.setText("待放币");
                        tvTradeTip.setText("对方已付款，确认收款后释放china-A");
                        if (!TextUtils.isEmpty(orderDetail.getPaySuccessImg())) {
                            ivBuyerScreenSpot.setVisibility(View.VISIBLE);
                            llBuyerScrrenSpot.setVisibility(View.VISIBLE);
                            Glide.with(context).load(orderDetail.getPaySuccessImg()).error(R.mipmap.ic_alipay).into(ivBuyerScreenSpot);
                        } else {
                            ivBuyerScreenSpot.setVisibility(View.GONE);
                            llBuyerScrrenSpot.setVisibility(View.GONE);
                        }
                        tvLeftButton.setVisibility(View.VISIBLE);
                        tvRightButton.setText("释放china-A");
                        tvRightButton.setBackgroundResource(R.mipmap.ic_trade_confirm_pay_btn_enable_bg);
                        llHasSell.setVisibility(View.GONE);
                    }
                    break;
            }
        }
    }

    public void showConfirmSellDialog() {
        NiceDialog niceDialog = null;
        if (niceDialog == null) {
            niceDialog = NiceDialog.init();
            niceDialog.setLayoutId(R.layout.content_confirm_sell);
            niceDialog.setConvertListener(new ViewConvertListener() {
                @Override
                protected void convertView(com.othershe.nicedialog.ViewHolder holder, final BaseNiceDialog dialog) {
                    LinearLayout llDismiss = holder.getView(R.id.ll_dismiss);
                    TextView tvConfirm = holder.getView(R.id.tv_confirm);
                    TextView tvCancel = holder.getView(R.id.tv_cancel);

                    llDismiss.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();
                        }
                    });
                    tvCancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();

                        }
                    });

                    tvConfirm.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();
                            JSONObject param = new JSONObject();
                            try {
                                param.put("orderid", orderDetail.getOrderNo());
                                param.put("orderid2", orderDetail.getMatchingOrderNo());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            presenter.confirmPayGte(param.toString());


                        }
                    });

                }
            });
            niceDialog.setAnimStyle(R.style.popwin_anim_style);
            niceDialog.setDimAmount(0.3f);
            niceDialog.setMargin(50);
            niceDialog.setShowBottom(false);
            niceDialog.setOutCancel(false);

        }
        niceDialog.show(getSupportFragmentManager());
    }


    @OnClick({R.id.iv_back, R.id.tv_left_button, R.id.tv_right_button, R.id.iv_buyer_pay_screen_spot, R.id.iv_make_call, R.id.iv_qrcode})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_buyer_pay_screen_spot:
                List<String> imgList = new ArrayList<>();
                imgList.add(orderDetail.getPaySuccessImg());
                startActivity(ImageShowActivity.createIntent(context, imgList, 0));
                break;
            case R.id.tv_left_button:
                startActivity(TradeComplainInputActivity.createIntent(context, orderDetail));
                break;
            case R.id.tv_right_button:
                if (orderDetail.getPayStatus() == 1) {
                    showConfirmSellDialog();
                } else {
                    ToastUtil.getInstance().shortLength(context, "对方还未上传支付截图");
                }
                break;
            case R.id.iv_make_call:
                PhoneUtil.makeCall(context, orderDetail.getMatchingUserPhone());
                break;
            case R.id.iv_qrcode:
                if (alertDialogWithShowQrCode == null) {
                    showDialogWithSetView();
                } else {
                    alertDialogWithShowQrCode.show();
                }
                break;
        }
    }


    void showDialogWithSetView() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.content_alipay_qrcode, null);
        ImageView ivQrcode = (ImageView) layout.findViewById(R.id.iv_alipay_qrcode);
        Bitmap bitmapWithQRCode = CodeUtils.createImage(orderDetail.getAuthAliPayAccount(), 400, 400, null);
        if (bitmapWithQRCode != null) {
            ivQrcode.setImageBitmap(bitmapWithQRCode);
        } else {
            ToastUtil.getInstance().shortLength(context, "二维码生成失败");
        }
        alertDialogWithShowQrCode = builder.setView(layout).create();
        alertDialogWithShowQrCode = builder.setView(layout).create();
        alertDialogWithShowQrCode.setTitle("支付宝账号");
        alertDialogWithShowQrCode.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        alertDialogWithShowQrCode.setCancelable(true);//false-dialog弹出后会点击返回键，dialog不消失; true-点击返回键可消失;要想消失可以调用dismiss方法
        alertDialogWithShowQrCode.setCanceledOnTouchOutside(true);//false-点击对话框以外的区域,dialog不消失; true-点击对话框以外区域,dialog消失.
        //先调用show这个方法，然后才设置dialog的长宽
        alertDialogWithShowQrCode.show();
    }


    @Override
    public void onqueryOrderDetailSuccess(EntityOrderDetail orderDetail) {
        super.onqueryOrderDetailSuccess(orderDetail);
        this.orderDetail = orderDetail;
        updatePayInfoView();
    }

    @Override
    public void onqueryOrderDetailFail(Exception e) {
        super.onqueryOrderDetailFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage());
        llOperatorContainer.setVisibility(View.GONE);
    }

    @Override
    public void onConfirmPayGteSuccess() {
        super.onConfirmPayGteSuccess();
        ToastUtil.getInstance().shortLength(context, "成功放币");
        isReleaseBiSuccess = true;
        updatePayInfoView();
        finish();

    }

    @Override
    public void onConfirmPayGteFail(Exception e) {
        super.onConfirmPayGteFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage());
    }


}
